<template >
  <div class="roadmap-container">
    <a-row>
      <a-col :span="16" class="list-container">
        <a-row class="operate-row">
          <a-col :span="10">{{$t('hangManage.roadList')}}</a-col>
          <a-col :span="14" class="text-right">
            <a-space>
              <a-button type="primary" @click="exportTable" >{{ $t('common.outputExcel') }}</a-button>
              <a-button type="primary" @click="toggleAll(true)">{{ $t('common.expandAll') }}</a-button>
              <a-button type="primary" @click="toggleAll(false)">{{ $t('common.packUpAll') }}</a-button>
              <a-button type="warning" @click="clearList" v-if="!disabled">{{ $t('common.clearList') }}</a-button>
            </a-space>
          </a-col>
        </a-row>
        <header>
          <div
            v-for="(item, index) in disabled ? viewRouteHeader : routeHeader"
            :key="index"
          >
            {{ item }}
          </div>
        </header>
        <a-spin :spinning="loading">
          <draggable
            :list="tableList"
            is="draggable"
            :disabled="disabled"
            handle=".process-box"
            animation="300"
            :scroll="true"
            filter=".forbid"
            force-fallback="true"
            group="out"
            item-key="index"
            :allbackOnBody="true"
            @add="add"
            @sort="handleSort"
            @start="handleStart"
            style="min-height: calc(100vh - 515px)"
          >
            <template #item="{ element, index }">
              <div>
                <div class="relative">
                  <span class="toggle-box forbid">
                    <img
                      v-if="element.forwardMerge"
                      src="../../../../assets/images/merge.png"
                      alt="#"
                    />
                    <minus-square-outlined
                      v-else-if="element.open"
                      @click="
                        () => {
                          element.open = false;
                        }
                      "
                    />
                    <plus-square-outlined
                      v-else
                      @click="
                        () => {
                          element.open = true;
                        }
                      "
                    />
                  </span>
                  <div
                    class="mt-12 process-box"
                    :class="
                      element.moProcRoadmapProcStationList?.length > 0
                        ? ''
                        : element.forwardMerge
                        ? 'process-box-merge'
                        : 'process-box-empty'
                    "
                  >
                    <div>
                      <span>{{ element.sort }}</span>
                    </div>
                    <div>
                      <a-checkbox
                        class="forbid"
                        :disabled="disabled"
                        v-model:checked="element.effect"
                        @change="(e) => changeProcessInfo(!e.target.checked)"
                        >{{ $t('hangManage.effect') }}</a-checkbox
                      >
                    </div>
                    <div>
                      <a-checkbox
                        class="forbid"
                        :disabled="disabled"
                        v-model:checked="element.forwardMerge"
                        @change="onCheckChange(element)"
                        >{{ $t('other.forwardMerge') }}</a-checkbox
                      >
                    </div>
                    <div>{{ element.processNo }}，{{ element.name }}</div>
                    <div class="forbid"></div>
                    <div v-if="!disabled" class="forbid">
                      <span
                        class="close-icon"
                        v-if="index != 0"
                        @click="handelCancel(index, false)"
                      >
                        <close-outlined />
                      </span>
                    </div>
                  </div>
                </div>
                <draggable
                  v-model="element.moProcRoadmapProcStationList"
                  filter=".nodrag"
                  is="draggable"
                  animation="300"
                  force-fallback="true"
                  group="inner"
                  item-key="index"
                  :allbackOnBody="true"
                  @add="addInner"
                  :disabled="disabled"
                  @start="handleInnerStart"
                >
                  <template v-slot:item="item">
                    <div class="site-box" v-if="element.open">
                      <div class="relative">
                        <span class="line-icon">
                          <environment-two-tone two-tone-color="#3E8FF7" />
                        </span>
                        <span class="pl-15">
                          {{ item.element.lineNo }}-{{ item.element.stationNo }}
                        </span>
                      </div>
                      <div>
                        <a-checkbox
                          v-model:checked="item.element.mainStationBoolean"
                          :disabled="disabled"
                          class="nodrag"
                          >{{ $t('other.assistSit') }}</a-checkbox
                        >
                      </div>
                      <div>
                        {{ item.element.proportion }}
                        <a-checkbox
                          v-model:checked="item.element.receiveHangerBoolean"
                          :disabled="disabled"
                          class="nodrag"
                          >{{ $t('hangManage.receiveHanger') }}</a-checkbox
                        >
                      </div>
                      <div>
                        {{
                          item.element.type == 1
                            ? $t('other.save')
                              : item.element.type == 2
                            ? $t('other.rework')
                            : $t('other.normal')
                        }}
                        <span v-if="showMsg(item.element, 'all')"> ，（ </span>
                        <span v-if="showMsg(item.element, 'color')"
                          >{{$t('basicData.color') }}：{{ item.element.colorList.join(",") }}；</span
                        >
                        <span v-if="showMsg(item.element, 'size')"
                          >{{ $t('basicData.size') }}： {{ item.element.sizeList.join(",") }}；</span
                        >
                        <span v-if="showMsg(item.element, 'po')"
                          >PO： {{ item.element.poList.join(",") }}；</span
                        >
                        <span v-if="showMsg(item.element, 'cutterNo')"
                          >{{$t('hangManage.bedNo')}}：
                          {{ item.element.cutterNoList.join(",") }}；</span
                        >
                        <span v-if="showMsg(item.element, 'tailorBill')"
                          >{{$t('hangManage.cut')}}：
                          {{ item.element.tailorBillList.join(",") }}</span
                        >
                        <span v-if="showMsg(item.element, 'all')"> ）</span>
                      </div>

                      <div>
                        <span v-if="item.element.staffId">
                          {{
                            getFieldText(
                              staffList,
                              item.element.staffId,
                              "id",
                              "staffNo"
                            )
                          }}-{{
                            getFieldText(
                              staffList,
                              item.element.staffId,
                              "id",
                              "nickName"
                            )
                          }}
                          {{
                            getFieldText(
                              staffList,
                              item.element.staffId,
                              "id",
                              "skillGrade"
                            )
                          }}
                          {{
                            arrToStr(
                              staffList,
                              item.element.staffId,
                              "id",
                              "professionNameList"
                            )
                          }}
                        </span>
                      </div>

                      <div v-if="!disabled" class="nodrag">
                        <a-button
                          type="link"
                          class="primary-link"
                          @click="editSite(index, item.index, item.element)"
                          >{{ $t('common.editor') }}</a-button
                        >
                        <span
                          class="close-icon"
                          @click="handelCancel(item.index, true, index)"
                        >
                          <close-outlined />
                        </span>
                      </div>
                    </div>
                  </template>
                </draggable>
              </div>
            </template>
          </draggable>
        </a-spin>
      </a-col>
      <a-col :span="8" class="choose-container">
        <chooseList
          ref="chooseListRef"
          :moId="props.moId"
          :processId="processId"
          :tableList="tableList"
          @onOutGroupEnd="onOutGroupEnd"
          @onChooseProcess="onChooseProcess"
          @onInnerGroupEnd="onInnerGroupEnd"
          :operateType="props.operateType"
        />
      </a-col>
    </a-row>
    <editStation ref="editStationRef" @ok="onStationOK" />
  </div>
</template>

<script setup>
import draggable from "vuedraggable";
import { ref, watch, nextTick, onMounted } from "vue";
import { routeHeader, viewRouteHeader } from "./routeChartConfig";
import {
  PlusSquareOutlined,
  MinusSquareOutlined,
  CloseOutlined,
  EnvironmentTwoTone,
} from "@ant-design/icons-vue";
import chooseList from "./chooseList.vue";
import editStation from "./editStation.vue";
import { cloneDeep, uniqBy } from "lodash";
import { message } from "ant-design-vue";
import axios from "@/utils/request";
import { getFieldText } from "@/utils";
import i18n from '@/locales/index'
const { t } = i18n.global

let emits = defineEmits(["initFormInfo", "onProcessInfo"]);
let props = defineProps({
  roueteVersionId: {
    require: true,
    default: () => null,
  },
  moId: {
    require: true,
    default: () => null,
  },
  moInfo: {
    require: true,
    default: () => {},
  },
  operateType: {
    require: true,
    default: () => "",
  },
});
let disabled = ref(false);
let loading = ref(false);
let editStationRef = ref();
let tableList = ref([]);
let routeInfo = ref({});
let chooseListRef = ref({});
let originList = ref(tableList.value);
let sortFlag = ref(false);
let sortInnerFlag = ref(false);
let processId = ref(null); // 工序版本id
let editProcIndex = ref(0);
let editStationIndex = ref(0);
let isAdd = ref(false);
let isEdit = ref(false);
let originSortList = ref([]);
let maxNum = ref(0);

let staffList = ref([]);
const arrToStr = (ary, value, itemName, field) => {
  const info = ary.filter((i) => i[itemName] == value);
  let arr = info.length ? info[0][field] : [];
  return arr ? `(${arr.join(",")})` : "";
};
const handleStart = () => {
  sortFlag.value = true;
  originList.value = cloneDeep(tableList.value);
};
const changeProcessInfo = (isDelete) => {
  let optList = tableList.value.filter((i) => i.effect);
  emits("onProcessInfo", optList, isDelete);
};
const add = async (e) => {
  console.log(e);
  sortFlag.value = false;
  await nextTick();
  // if (e.newIndex === 0) {
  //   message.warning("第一站只能是挂片站");
  //   tableList.value.splice(0, 1);
  //   initSortInfo();
  // }
  changeProcessInfo();
};
const handleSort = (e) => {
  if (sortFlag.value) {
    // console.log(tableList.value, "-----tableList.value---");
    if (
      e.oldIndex == 0 &&
      tableList.value[e.newIndex].moProcRoadmapProcStationList?.length > 0 &&
      tableList.value[e.newIndex].moProcRoadmapProcStationList.some(
        (i) => i.role == "2"
      )
    ) {
      message.warning(t('other.firstProcessHaveHangerCanNotMove'));
      tableList.value = originList.value;
    } else if (
      e.newIndex == 0 &&
      originList.value[e.newIndex].moProcRoadmapProcStationList?.length > 0 &&
      originList.value[e.newIndex].moProcRoadmapProcStationList.some(
        (i) => i.role == "2"
      )
    ) {
      message.warning(t('other.firstProcessHaveHangerCanNotMoveUp'));
      tableList.value = originList.value;
    } else {
      initSortInfo();
      tableList.value.forEach((i, index) => {
        i.sort = originSortList.value[index];
      });
    }
    changeProcessInfo();

    // if (e.newIndex == 0) {
    //   message.warning("第一道只能是挂片工序");
    //   tableList.value = originList.value;
    // } else {
    //   initSortInfo();
    //   tableList.value.forEach((i, index) => {
    //     i.sort = originSortList.value[index];
    //   });
    // }
  }
};
const handelCancel = (key, isInner, outKey) => {
  if (isInner) {
    tableList.value[outKey].moProcRoadmapProcStationList.splice(key, 1);
  } else {
    tableList.value.splice(key, 1);
    initSortInfo();
    changeProcessInfo(true);
  }
};
const onOutGroupEnd = () => {
  tableList.value = tableList.value.map((i) => {
    let obj = { ...i };
    if (obj.open == undefined) obj.open = true;
    obj.moProcRoadmapProcStationList = obj.moProcRoadmapProcStationList || [];
    if (!obj.sort) {
      let newSortNo = ++maxNum.value;
      obj.sort = newSortNo;
    }
    return obj;
  });
  initSortInfo();

  tableList.value.forEach((i, index) => {
    i.sort = originSortList.value[index];
  });
};
const handleInnerStart = () => {
  sortInnerFlag.value = true;
  originList.value = cloneDeep(tableList.value);
};
const onSortInner = () => {
  let lists = cloneDeep(tableList.value);
  let flag1 = lists[0].moProcRoadmapProcStationList.some((i) => i.role != "2");
  lists.splice(0, 1);
  let flag2 = lists
    .reduce((prev, next) => {
      return prev.concat(
        ...(next.moProcRoadmapProcStationList
          ? next.moProcRoadmapProcStationList
          : [])
      );
    }, [])
    .some((i) => i.role == 2);
  // if (flag1) message.warning("第一道工序只能选挂片站");
  if (flag2) message.warning(t('other.hangStationMustDownFirstProcessCanHang'));
  let mergeFlag = lists.some(
    (i) => i.forwardMerge && i.moProcRoadmapProcStationList.length > 0
  );
  if (mergeFlag) message.warning(t('other.forwardMergeProcess'));
  let isUniq = lists.every(
    (i) => isUniqInner(i.moProcRoadmapProcStationList).isUniq
  );
  if (flag1 || flag2 || mergeFlag || !isUniq)
    tableList.value = originList.value;
};
const isUniqInner = (list) => {
  let uniqList = uniqBy(list, "stationId");
  let isUniq = uniqList.length == list.length;
  if (!isUniq) message.warning(t('other.sameProcessCanNotSameStation'));
  return {
    isUniq,
    uniqList,
  };
};
const onAddInner = () => {
  tableList.value.forEach((el, index) => {
    if (index == 0) {
      if (
        el.moProcRoadmapProcStationList &&
        el.moProcRoadmapProcStationList.some((i) => i.role != "2")
      ) {
        // message.warning("第一道工序只能选挂片站");
        // el.moProcRoadmapProcStationList =
        //   el.moProcRoadmapProcStationList.filter((i) => i.role == "2");
      }
      let isUniqInfo = isUniqInner(el.moProcRoadmapProcStationList);
      if (!isUniqInfo.isUniq)
        el.moProcRoadmapProcStationList = isUniqInfo.uniqList;
    } else {
      if (el.forwardMerge) {
        if (el.moProcRoadmapProcStationList.length > 0) {
          message.warning(t('other.forwardMergeProcess'));
          el.moProcRoadmapProcStationList = [];
        }
      } else {
        if (
          el.moProcRoadmapProcStationList &&
          el.moProcRoadmapProcStationList.some((i) => i.role == "2")
        ) {
          message.warning(t('other.hangStationMustDownFirstProcessCanHang'));
          el.moProcRoadmapProcStationList =
            el.moProcRoadmapProcStationList.filter((i) => i.role != "2");
        }

        let isUniqInfo = isUniqInner(el.moProcRoadmapProcStationList);
        if (!isUniqInfo.isUniq)
          el.moProcRoadmapProcStationList = isUniqInfo.uniqList;
      }
    }
  });
};
const addInner = async () => {
  await nextTick();
  if (sortInnerFlag.value) {
    onSortInner();
  } else {
    onAddInner();
  }
  sortInnerFlag.value = false;
};
const onInnerGroupEnd = () => {
  tableList.value.map((el) => {
    el.moProcRoadmapProcStationList = el.moProcRoadmapProcStationList.map(
      (i) => ({ ...i })
    );
    return el;
  });
};
const toggleAll = (open) => {
  tableList.value.forEach((i) => {
    i.open = open;
  });
};
const clearList = () => {
  let lists = cloneDeep(tableList.value).splice(0, 1);
  lists[0].moProcRoadmapProcStationList = [];
  tableList.value = lists;
  initSortInfo();
  changeProcessInfo(true);
};
const onCheckChange = (element) => {
  if (element.forwardMerge) element.moProcRoadmapProcStationList = [];
};
const editSite = (parentIndex, index, record) => {
  let name = `${record.lineNo}-${record.stationNo}`;
  editProcIndex.value = parentIndex;
  editStationIndex.value = index;
  editStationRef.value.edit(
    name,
    record,
    props.moInfo,
    props.staffList || staffList.value
  );
};
const onStationOK = (value) => {
  let datas = cloneDeep(tableList.value);
  datas.forEach((item, index) => {
    if (index == editProcIndex.value) {
      item.moProcRoadmapProcStationList &&
        item.moProcRoadmapProcStationList.map((el, i) => {
          if (i == editStationIndex.value) {
            Object.assign(el, value);
          }
          return el;
        });
    }
  });
  tableList.value = datas;
};

const initSortInfo = () => {
  originSortList.value = tableList.value
    .map((i) => i.sort)
    .filter((i) => i != undefined)
    .sort((a, b) => a - b);
  maxNum.value = Math.max(...originSortList.value);
};
const initTableList = (list, isNew) => {
  list.forEach((i) => {
    i.open = true;
    i.forwardMerge = i.forwardIntegration == 1;
    i.enable = isNew ? 1 : i.enable;
    i.effect = i.enable == 1;
    if (i.moProcRoadmapProcStationList) {
      i.moProcRoadmapProcStationList.forEach((i) => {
        i.mainStationBoolean = i.mainAuxiliaryStation == 2;
        i.receiveHangerBoolean = i.receiveHanger == 1;
      });
    } else {
      i.moProcRoadmapProcStationList = [];
    }
  });
  tableList.value = list;
  initSortInfo();
};
const initRouteListInfo = (info) => {
  routeInfo.value = info;
  processId.value = isAdd.value ? null : info.processId;
  initTableList(info.moProcRoadmapProcList || []);
  changeProcessInfo();
};
// 路线图详细信息
const getVersionRouteInfo = async (versionId) => {
  loading.value = true;
  try {
    const res = await axios.getAction("/api/mo/mo-proc-roadmap/get", {
      id: versionId,
    });
    emits("initFormInfo", res.data || {});
    initRouteListInfo(res.data || {});
  } catch {
    routeInfo.value = {};
  }
  loading.value = false;
};

const exportTable = async () => {
  let param = { id: props.roueteVersionId }
  try {
    console.log(2222)
    exportExcels('/api/mo/mo-proc-roadmap/export-mo-technology-diagram', "路线图", true, param);
  }catch (e) {
    console.log(e)
  }
};
const exportExcels = (exportUrl, fileName, needParams = false, params) => {

  if (!fileName || typeof fileName != 'string') {
    fileName = '导出文件'
  }
  let param = params;
  axios.downFile(exportUrl, needParams ? param : null).then((data) => {
    console.log(data)
    if (!data) {
      return
    }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data]), fileName + '.xlsx')
    } else {
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName + '.xlsx')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) // 下载完成移除元素
      window.URL.revokeObjectURL(url) // 释放掉blob对象
    }
  })
};
const showMsg = (record, type) => {
  if (type == "all") {
    return [
      "colorList",
      "sizeList",
      "poList",
      "cutterNoList",
      "tailorBillList",
    ].some((i) => record[i] && record[i].length);
  } else {
    return record[`${type}List`] && record[`${type}List`].length;
  }
};
const onChooseProcess = (list, processVersionId) => {
  list.forEach((i, index) => {
    i.sort = index + 1;
  });
  initTableList(list, true);
  changeProcessInfo();
  // processOption.value = tableList.value.filter(i => i.effect)
  processId.value = processVersionId;
};

defineExpose({
  processId,
  tableList,
});
watch(
  () => props.roueteVersionId,
  (newVal) => {
    tableList.value = [];
    originSortList.value = [];
    if (newVal && !isAdd.value) getVersionRouteInfo(newVal);
  },
  { deep: true, immediate: true }
);
watch(
  () => props.operateType,
  (newVal) => {
    disabled.value = newVal == "view";
    isAdd.value = newVal == "add";
    isEdit.value = newVal == "edit";
  },
  { deep: true, immediate: true }
);

onMounted(async () => {
  const resStaff = await axios.postAction("/api/basic/staff/list");
  if (resStaff.success) staffList.value = resStaff.data;
});
</script>